﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Configuration.Provider;
using System.Web.UI;
using System.Xml.Linq;
using System.Web.UI.HtmlControls;
using System.Globalization;
using Formsy.Common;
using Formsy.Config;

namespace Formsy.Providers.Regionalization
{
    public abstract class RegionalizationProvider : ProviderBase
    {
        /// <summary>
        /// Iterates through xml, replaces field labels with regionalized ones from xml.
        /// </summary>
        /// <param name="formFields"></param>
        /// <param name="x"></param>
        public virtual void RegionalizeLabels(List<FormField> formFields, XElement x)
        {
            var xmlFields = x.Descendants("Field");

            // iterate through items and assign labels
            foreach (var xmlField in xmlFields)
            {
                var fieldName = xmlField.GetName();

                // get formField which has a fieldName that matches fieldName
                var field = (FormField)formFields
                                    .Where(c => c.FieldName == fieldName)
                                    .Single();

                // get region values from xml
                var xmlRegions = xmlField
                                    .Descendants("Label")
                                    .Single()
                                    .Descendants("Region");

                field.Label.Text = GetRegionalizedValue(xmlRegions);
            }
        }



        public virtual void RegionalizeValidatiionMessages(List<FormField> formFields, XElement xml)
        {
            var xmlFields = xml.Descendants("Field");

            // iterate through fieldXml and assign labels
            foreach (var xmlField in xmlFields)
            {
                // get field name
                var fieldName = xmlField.GetName();

                // get formField which it has a fieldName that matches fieldName
                var field = formFields
                                .Where(x => x.FieldName == fieldName)
                                .Single();

                // get list of validators from xml
                var xmlVals = xmlField.Descendants("Validator");

                // for each validator in xml, find the field, then set regionalized message 
                foreach (var xmlVal in xmlVals)
                {
                    var type = xmlVal.Attribute("Type").Value; // get type of validator

                    // get validator from field where the validator type == type 
                    var val = field
                                .Validators
                                .Where(x => x.Type == type)
                                .Select(x => (BaseValidator)x.Control)
                                .FirstOrDefault(); // note: we can only currently support one custom validator!

                    // get region values from xml
                    var xmlRegions = xmlVal
                                    .Descendants("ValidationMessage")
                                    .FirstOrDefault()
                                    .Descendants("Region");
                    if (xmlRegions != null)
                        val.ErrorMessage = GetRegionalizedValue(xmlRegions);
                }
            }
        }


        public virtual void RegionalizeRegex(List<FormField> formFields, XElement xml)
        {
            var xmlFields = xml.Descendants("Field");

            // iterate through fieldXml and assign labels
            foreach (var xmlField in xmlFields)
            {
                // get field name
                var fieldName = xmlField.GetName();

                // get formField which it has a fieldName that matches fieldName
                var field = formFields
                                .Where(x => x.FieldName == fieldName)
                                .Single();

                // get validator from xml
                var xmlVal = xmlField
                                    .Descendants("Validator")
                                    .Where(x => x.Attribute("Type").Value == ControlType.RegularExpressionValidator)
                                    .FirstOrDefault(); // there can be only one regex validator!

                if (xmlVal != null)
                {
                    var reg = field
                                .Validators
                                .Where(x => x.Control as RegularExpressionValidator != null)
                                .Single();
                    var xmlRegions = xmlVal.Descendants("RegularExpression").Single().Descendants("Region"); // can only be one regular expression node with regions
                    if (xmlRegions != null)
                        ((RegularExpressionValidator)reg.Control).ValidationExpression = GetRegionalizedValue(xmlRegions);
                }
            }
        }


        /// <summary>
        /// Returns the value for the current region.
        /// </summary>
        /// <param name="regions"></param>
        /// <returns></returns>
        protected virtual string GetRegionalizedValue(IEnumerable<XElement> regions)
        {
            return (string)regions
                        .Where(x => x.Attribute("Name").Value == GetRegion())
                        .Select(x => x.Value).Single();
        }


        /// <summary>
        /// Returns the current culture. When overrided, the region returned may be customized to anything.
        /// </summary>
        /// <returns></returns>
        protected virtual string GetRegion()
        {
            return CultureInfo.CurrentUICulture.Name;
        }
    }


    public class RegionalizationProviderCollection : ProviderCollection
    {
        // Return an instance of DataProvider
        // for a specified provider name
        new public RegionalizationProvider this[string name]
        {
            get { return (RegionalizationProvider)base[name]; }
        }
    }
}

